Popular Searches
Popular Course Categories
Popular Courses

Understanding RIGHT JOIN

Understanding RIGHT JOIN

Joins and Relationships Between Tables

Understanding RIGHT JOIN in MySQL

Course: MySQL Training Course

Topic: Understanding RIGHT JOIN

Course Link: MySQL Training Course

Demo Link: Register for a Course Demo


1. Introduction to RIGHT JOIN

In MySQL, RIGHT JOIN is used to combine data from two tables while preserving every row from the right-hand table. When a row in the right-hand table has a matching record in the left-hand table, MySQL combines their columns. When no matching record exists, the columns from the left-hand table contain NULL.

In relational databases, information is commonly stored in multiple related tables. For example, a company might store employee details in an employees table and department information in a departments table. A RIGHT JOIN can display every department, including departments that currently have no employees.

The most important concept is that RIGHT JOIN preserves all rows from the table written after RIGHT JOIN, regardless of whether matching rows exist in the table written before it.

1.1 Learning Objectives

  • Understand the purpose and behavior of RIGHT JOIN in MySQL.
  • Learn the syntax and structure of RIGHT JOIN queries.
  • Understand the role of the ON and USING clauses.
  • Identify matching and unmatched records in joined tables.
  • Use RIGHT JOIN with WHERE, ORDER BY, GROUP BY, and aggregate functions.
  • Join three or more tables using RIGHT JOIN.
  • Find records in the right-hand table that have no matching records in the left-hand table.
  • Compare RIGHT JOIN with INNER JOIN and LEFT JOIN.
  • Identify common RIGHT JOIN mistakes and performance considerations.

2. What Is RIGHT JOIN?

RIGHT JOIN, also called RIGHT OUTER JOIN, is a SQL operation that returns all rows from the right-hand table and matching rows from the left-hand table.

Suppose there are two tables:

  • employees: stores employee IDs, employee names, and department IDs.
  • departments: stores department IDs and department names.

If you want to list every department, even when no employee belongs to a department, you can use RIGHT JOIN with departments as the right-hand table.

2.1 Key Characteristics of RIGHT JOIN

  • Returns every row from the right-hand table.
  • Returns matching records from the left-hand table.
  • Uses NULL values for left-table columns when a match does not exist.
  • Can combine columns from multiple related tables.
  • Supports filtering, sorting, grouping, and aggregate calculations.
  • Can be used to identify right-table records without corresponding left-table records.

2.2 Real-World Applications

Industry Tables Purpose
Human Resources Employees and Departments Display every department, including empty departments.
Education Students and Courses List all courses, including courses without enrolled students.
E-commerce Order Items and Products List all products, including products not included in any order.
Banking Transactions and Accounts Display all accounts, including accounts without transactions.
Healthcare Appointments and Doctors List all doctors, including doctors without appointments.
Inventory Stock Movements and Warehouses Display all warehouses, including those without stock movements.

3. Understanding Left and Right Tables

To understand RIGHT JOIN, you must identify which table is on the left and which table is on the right in the SQL statement.

Consider this query:

SELECT
    e.employee_name,
    d.department_name
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id;

In this query:

  • employees is the left-hand table because it appears after FROM.
  • departments is the right-hand table because it appears after RIGHT JOIN.
  • All departments are included in the result.
  • Employee details appear when a matching department relationship exists.
  • Departments without matching employees still appear, with NULL employee columns.

3.1 Important Rule

The table position determines which records are preserved. In RIGHT JOIN, the table after the RIGHT JOIN keyword is the table whose rows must all appear in the result.

4. Basic Syntax of RIGHT JOIN

The general syntax of RIGHT JOIN in MySQL is:

SELECT
    table1.column_name,
    table2.column_name
FROM table1
RIGHT JOIN table2
    ON table1.common_column = table2.common_column;

4.1 Explanation of the Syntax

SQL Component Explanation
SELECT Specifies the columns to display.
FROM Identifies the left-hand table.
RIGHT JOIN Joins the second table while preserving every row from it.
ON Defines the condition for matching records.
table1.column_name References a column from the left-hand table.
table2.column_name References a column from the right-hand table.

4.2 RIGHT JOIN and RIGHT OUTER JOIN

In MySQL, RIGHT JOIN and RIGHT OUTER JOIN have the same meaning. The word OUTER is optional.

SELECT e.employee_name, d.department_name
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id;
SELECT e.employee_name, d.department_name
FROM employees AS e
RIGHT OUTER JOIN departments AS d
    ON e.department_id = d.department_id;

Both queries preserve all rows from the departments table.

5. Creating Sample Tables for Practice

Let's create two sample tables to understand how RIGHT JOIN works in real queries.

5.1 Create a Database

CREATE DATABASE right_join_practice;
USE right_join_practice;

5.2 Create the Employees Table

CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    employee_name VARCHAR(100) NOT NULL,
    department_id INT,
    salary DECIMAL(10,2)
);

5.3 Create the Departments Table

CREATE TABLE departments (
    department_id INT PRIMARY KEY,
    department_name VARCHAR(100) NOT NULL,
    location VARCHAR(100)
);

These tables contain department IDs that can be used to match employees with departments. This example does not define a foreign key, so it can also be used to demonstrate unmatched records.

5.4 Insert Sample Department Records

INSERT INTO departments
(department_id, department_name, location)
VALUES
(10, 'IT', 'Mumbai'),
(20, 'HR', 'Pune'),
(30, 'Sales', 'Delhi'),
(40, 'Marketing', 'Nashik'),
(50, 'Finance', 'Bengaluru');

5.5 Insert Sample Employee Records

INSERT INTO employees
(employee_id, employee_name, department_id, salary)
VALUES
(1, 'Amit', 10, 60000.00),
(2, 'Priya', 20, 45000.00),
(3, 'Rahul', 10, 70000.00),
(4, 'Neha', 30, 50000.00),
(5, 'Vikas', 20, 48000.00);

5.6 View the Sample Data

SELECT * FROM employees;
SELECT * FROM departments;

The employees table contains employees from IT, HR, and Sales. The Marketing and Finance departments have no employees in this sample data.

6. Performing Your First RIGHT JOIN

Suppose you want to display every department and the names of employees assigned to it. Even departments without employees must appear in the result.

6.1 Query

SELECT
    e.employee_id,
    e.employee_name,
    d.department_id,
    d.department_name,
    d.location
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id
ORDER BY d.department_id;

6.2 Expected Output

employee_id employee_name department_id department_name location
1 Amit 10 IT Mumbai
3 Rahul 10 IT Mumbai
2 Priya 20 HR Pune
5 Vikas 20 HR Pune
4 Neha 30 Sales Delhi
NULL NULL 40 Marketing Nashik
NULL NULL 50 Finance Bengaluru

6.3 Explanation

  1. MySQL reads the employees and departments tables.
  2. The ON clause compares their department IDs.
  3. Matching employee and department rows are combined.
  4. All departments are retained because departments is the right-hand table.
  5. Marketing and Finance appear even though no employees match them.
  6. The employee columns for these unmatched departments contain NULL.

The IT and HR departments each appear twice because each has two employees. RIGHT JOIN returns one row per matching combination, so the number of output rows may be greater than the number of rows in the right-hand table.

7. Understanding the ON Clause

The ON clause specifies how MySQL matches records between tables. It is essential for connecting related information correctly.

7.1 Joining Using Department IDs

SELECT
    e.employee_name,
    d.department_name
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id;

MySQL compares the department ID in each employee record with the department ID in the departments table. If the values match, the employee and department details appear together.

7.2 Joining on Different Column Names

The matching columns do not need to have identical names. They must represent compatible values and the intended relationship.

SELECT
    e.employee_name,
    d.department_name
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.id;

This example assumes the departments table has a column named id instead of department_id. Adjust the query to match your actual table structure.

7.3 Joining with Multiple Conditions

You can include multiple conditions in the ON clause when the relationship requires them.

SELECT
    a.employee_id,
    b.project_id
FROM employee_assignments AS a
RIGHT JOIN project_assignments AS b
    ON a.employee_id = b.employee_id
    AND a.project_id = b.project_id;

This example assumes both tables contain the listed columns. Both conditions must be satisfied for the records to match.

8. Using Table Aliases in RIGHT JOIN

A table alias is a temporary name assigned to a table within a query. Aliases help reduce repetition and improve readability.

8.1 Query Without Aliases

SELECT
    employees.employee_name,
    departments.department_name
FROM employees
RIGHT JOIN departments
    ON employees.department_id = departments.department_id;

8.2 Query With Aliases

SELECT
    e.employee_name,
    d.department_name
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id;

8.3 Benefits of Table Aliases

  • Make queries shorter and easier to read.
  • Help distinguish columns from different tables.
  • Improve readability in queries with multiple joins.
  • Reduce repeated references to long table names.

Once an alias is assigned, use that alias consistently when referring to the table's columns.

9. Selecting Specific Columns

When using RIGHT JOIN, you can select only the columns needed for your report rather than retrieving every column from both tables.

9.1 Display Department Names and Employee Names

SELECT
    d.department_name,
    e.employee_name
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id;

9.2 Display Department Locations and Salaries

SELECT
    d.department_name,
    d.location,
    e.employee_name,
    e.salary
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id;

9.3 Using SELECT *

SELECT *
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id;

SELECT * returns all columns from both tables. For reports and production queries, selecting columns explicitly is usually clearer and avoids confusing duplicate column names.

10. RIGHT JOIN with WHERE

The WHERE clause filters the rows produced by the join. When using RIGHT JOIN, be careful not to unintentionally remove unmatched right-table rows.

10.1 Display Departments Located in Mumbai

SELECT
    e.employee_name,
    d.department_name,
    d.location
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id
WHERE d.location = 'Mumbai';

This query returns matching records for departments located in Mumbai. It retains the right-table preservation behavior only for rows satisfying the WHERE condition.

10.2 Display All Departments with Employee Salaries Above 50,000

SELECT
    e.employee_name,
    e.salary,
    d.department_name
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id
WHERE e.salary > 50000;

This query returns only joined rows with an employee salary greater than 50,000. Departments without employees are removed because their employee salary is NULL and the WHERE condition is not true for those rows.

10.3 Preserve Unmatched Departments While Filtering Employees

If the goal is to keep every department but match only employees whose salary is above 50,000, put the employee condition in the ON clause.

SELECT
    e.employee_name,
    e.salary,
    d.department_name
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id
    AND e.salary > 50000
ORDER BY d.department_id;

Here, departments remain in the result even when they have no employee who satisfies the salary condition. In such cases, the employee columns are NULL.

11. RIGHT JOIN with ORDER BY

The ORDER BY clause sorts the result set. You can sort by columns from either table.

11.1 Sort Departments by Department Name

SELECT
    e.employee_name,
    d.department_name
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id
ORDER BY d.department_name ASC;

11.2 Sort by Department ID and Employee Name

SELECT
    d.department_id,
    d.department_name,
    e.employee_name
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id
ORDER BY d.department_id ASC, e.employee_name ASC;

ASC sorts values in ascending order, while DESC sorts them in descending order.

12. RIGHT JOIN with COUNT()

The COUNT() function can be combined with RIGHT JOIN to count matching records while preserving all rows from the right-hand table.

12.1 Count Employees in Each Department

SELECT
    d.department_id,
    d.department_name,
    COUNT(e.employee_id) AS total_employees
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id
GROUP BY d.department_id, d.department_name
ORDER BY d.department_id;

12.2 Expected Output

department_id department_name total_employees
10 IT 2
20 HR 2
30 Sales 1
40 Marketing 0
50 Finance 0

Notice that COUNT(e.employee_id) returns zero for departments without employees because NULL values are not counted. Using COUNT(*) would count the preserved department row itself and return one for those unmatched departments, which is not the desired employee count.

13. RIGHT JOIN with SUM() and AVG()

RIGHT JOIN can also calculate salary totals and averages for each department.

13.1 Calculate Total Salary by Department

SELECT
    d.department_name,
    SUM(e.salary) AS total_salary
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id
GROUP BY d.department_id, d.department_name
ORDER BY d.department_id;

Departments without employees will have a NULL total salary because there are no non-NULL salary values to sum. Use COALESCE() if the report should display zero instead.

SELECT
    d.department_name,
    COALESCE(SUM(e.salary), 0) AS total_salary
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id
GROUP BY d.department_id, d.department_name;

13.2 Calculate Average Salary by Department

SELECT
    d.department_name,
    AVG(e.salary) AS average_salary
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id
GROUP BY d.department_id, d.department_name;

For departments without employees, the average salary is NULL because no salary values are available for the calculation.

14. RIGHT JOIN with HAVING

The HAVING clause filters grouped results after aggregate calculations. It can be used to identify departments that meet a specific employee-count or salary requirement.

14.1 Departments with More Than One Employee

SELECT
    d.department_name,
    COUNT(e.employee_id) AS total_employees
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id
GROUP BY d.department_id, d.department_name
HAVING COUNT(e.employee_id) > 1;

14.2 Departments with Total Salary Above 100,000

SELECT
    d.department_name,
    SUM(e.salary) AS total_salary
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id
GROUP BY d.department_id, d.department_name
HAVING SUM(e.salary) > 100000;

14.3 WHERE Versus HAVING

Clause Purpose Example
WHERE Filters joined rows before grouping. WHERE e.salary > 50000
HAVING Filters grouped results after aggregation. HAVING COUNT(e.employee_id) > 1

15. Finding Departments Without Employees

A common use of RIGHT JOIN is finding records in the right-hand table that do not have matching records in the left-hand table.

15.1 Query

SELECT
    d.department_id,
    d.department_name
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id
WHERE e.employee_id IS NULL;

15.2 Expected Output

department_id department_name
40 Marketing
50 Finance

15.3 Explanation

  • RIGHT JOIN retains every department.
  • Departments with employees have matching employee IDs.
  • Departments without employees have NULL values in employee columns.
  • The WHERE clause selects only rows where the employee ID is NULL.

Using a non-NULLable column such as the employee primary key is a reliable way to identify unmatched rows.

16. RIGHT JOIN Between Three Tables

MySQL allows multiple joins in one query. This is useful when information is distributed across several related tables.

Suppose a training institute has the following tables:

  • students: contains student information.
  • enrollments: contains student enrollment records.
  • courses: contains all available courses.

16.1 Example Query

SELECT
    s.student_name,
    e.enrollment_date,
    c.course_name
FROM students AS s
INNER JOIN enrollments AS e
    ON s.student_id = e.student_id
RIGHT JOIN courses AS c
    ON e.course_id = c.course_id;

This example preserves every course in the courses table. However, because the first join is an INNER JOIN, students without enrollment records do not enter the intermediate result. For complex multi-join queries, carefully choose join order and join types based on which records must be preserved.

16.2 A Simpler Example with Three Tables

SELECT
    e.employee_name,
    d.department_name,
    l.location_name
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id
INNER JOIN department_locations AS l
    ON d.department_id = l.department_id;

This example assumes a department_locations table exists. Because an INNER JOIN follows the RIGHT JOIN, departments without a matching location record will be excluded from the final result. Join types should be selected according to the report requirements.

17. Using USING with RIGHT JOIN

When both tables have a matching column with the same name, MySQL supports the USING clause as an alternative to the ON clause.

17.1 Using ON

SELECT
    e.employee_name,
    d.department_name
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id;

17.2 Using USING

SELECT
    employee_name,
    department_id,
    department_name
FROM employees
RIGHT JOIN departments
    USING (department_id);

The USING clause requires the join column to exist in both tables. For SELECT statements, it treats the shared join column as one output column rather than displaying two separate copies of it.

17.3 ON Versus USING

Feature ON USING
Join condition Specifies an explicit comparison. Names shared columns.
Different column names Supported. Not supported for the join column.
Complex conditions Supports multiple conditions. Best for shared-column equality joins.
Readability Flexible and explicit. Compact when column names match.

18. RIGHT JOIN Versus INNER JOIN and LEFT JOIN

Understanding the differences between join types helps you choose the correct query for your requirements.

Join Type Rows Preserved Unmatched Rows
INNER JOIN Only matching rows from both tables. Excluded.
LEFT JOIN All rows from the left-hand table. Unmatched left-table rows remain; right-side columns become NULL.
RIGHT JOIN All rows from the right-hand table. Unmatched right-table rows remain; left-side columns become NULL.

18.1 INNER JOIN Example

SELECT e.employee_name, d.department_name
FROM employees AS e
INNER JOIN departments AS d
    ON e.department_id = d.department_id;

Only departments with matching employees appear.

18.2 LEFT JOIN Example

SELECT e.employee_name, d.department_name
FROM departments AS d
LEFT JOIN employees AS e
    ON e.department_id = d.department_id;

This query preserves all departments because departments is the left-hand table.

18.3 RIGHT JOIN Example

SELECT e.employee_name, d.department_name
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id;

This query also preserves all departments because departments is the right-hand table.

18.4 RIGHT JOIN Can Be Rewritten as LEFT JOIN

A RIGHT JOIN can be rewritten as a LEFT JOIN by reversing the order of the tables. The following queries are logically equivalent:

SELECT e.employee_name, d.department_name
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id;
SELECT e.employee_name, d.department_name
FROM departments AS d
LEFT JOIN employees AS e
    ON e.department_id = d.department_id;

Many developers prefer LEFT JOIN because it makes the preserved table easy to identify at the beginning of the query. Both forms can express the same relationship when written correctly.

19. Common RIGHT JOIN Mistakes

19.1 Confusing the Right-Hand Table

A common mistake is assuming that RIGHT JOIN preserves the table written after FROM. It actually preserves the table written after RIGHT JOIN.

SELECT e.employee_name, d.department_name
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id;

In this query, all departments are preserved, not all employees.

19.2 Forgetting the ON Clause

RIGHT JOIN requires a join condition in MySQL. Specify the relationship using ON or USING.

SELECT e.employee_name, d.department_name
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id;

19.3 Filtering Unmatched Rows Accidentally

A WHERE condition on the left-hand table can remove rows where that table's columns are NULL.

-- Unmatched departments are removed by this filter
SELECT e.employee_name, d.department_name
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id
WHERE e.salary > 50000;

If all departments must remain, consider placing the employee condition in the ON clause instead.

19.4 Using COUNT(*) Instead of COUNT(column)

When counting employees per department, COUNT(*) counts the preserved department row even when there is no employee match. Use COUNT(e.employee_id) when the goal is to count employees.

19.5 Unexpected Repeated Rows

A department may appear multiple times when it contains multiple employees. This is expected for a one-to-many relationship. Use GROUP BY and aggregate functions when the requirement is one summary row per department.

19.6 Using DISTINCT Without Understanding the Results

DISTINCT removes duplicate result rows, but it does not fix an incorrect join condition or an unexpected one-to-many relationship. Check the join logic before using it.

19.7 Incorrect NULL Comparisons

Use IS NULL or IS NOT NULL to test for NULL values. Expressions such as employee_id = NULL do not perform a correct NULL test.

20. RIGHT JOIN Performance and Best Practices

  • Use accurate join conditions based on the actual table relationships.
  • Identify the table whose rows must all be preserved before writing the query.
  • Use table aliases for clarity.
  • Select only the columns required for the report.
  • Use compatible data types for join columns.
  • Consider indexes on frequently joined columns for large datasets.
  • Use EXPLAIN to inspect the query execution plan.
  • Be careful with WHERE conditions on the non-preserved table.
  • Use COUNT(non_nullable_column) when counting matching records.
  • Use GROUP BY for summaries and HAVING for aggregate-based filtering.
  • Consider rewriting RIGHT JOIN as LEFT JOIN when it makes the query easier to read.
  • Test the query with matching and unmatched records to verify the output.

20.1 Checking a Query with EXPLAIN

EXPLAIN
SELECT
    e.employee_name,
    d.department_name
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id;

EXPLAIN provides information about how MySQL plans to execute a query, including table access methods and possible index usage. Optimization decisions should be based on the execution plan, indexes, data size, and query requirements.

21. Practical Project: Department and Employee Report

Project Objective: Create a department report that lists all departments, displays their employees when available, calculates employee counts, and identifies departments without employees.

21.1 Project Requirements

  • Display every department, including empty departments.
  • Display employee names when a matching employee exists.
  • Count the employees assigned to each department.
  • Calculate the total salary for each department.
  • Display zero instead of NULL for total salary when no employee exists.
  • Sort the report by department ID.

21.2 Project Solution

SELECT
    d.department_id,
    d.department_name,
    d.location,
    COUNT(e.employee_id) AS total_employees,
    COALESCE(SUM(e.salary), 0) AS total_salary
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id
GROUP BY
    d.department_id,
    d.department_name,
    d.location
ORDER BY d.department_id;

21.3 Find Departments Without Employees

SELECT
    d.department_id,
    d.department_name
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id
WHERE e.employee_id IS NULL
ORDER BY d.department_id;

21.4 Project Learning Outcomes

  • Preserve all records from a selected table.
  • Combine information from related tables.
  • Calculate department-level summaries.
  • Identify unmatched records using NULL checks.
  • Understand the effect of filtering conditions on outer joins.

22. Practice Exercises

Exercise 1: Display Every Department

Write a query to show every department and any matching employee names.

SELECT
    d.department_name,
    e.employee_name
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id;

Exercise 2: Count Employees per Department

Display every department and the number of matching employees.

SELECT
    d.department_name,
    COUNT(e.employee_id) AS total_employees
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id
GROUP BY d.department_id, d.department_name;

Exercise 3: Find Departments Without Employees

Write a query to list departments that have no matching employees.

SELECT
    d.department_id,
    d.department_name
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id
WHERE e.employee_id IS NULL;

Exercise 4: Calculate Total Salary by Department

Display all departments and their total salary, showing zero when there are no employees.

SELECT
    d.department_name,
    COALESCE(SUM(e.salary), 0) AS total_salary
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id
GROUP BY d.department_id, d.department_name;

Exercise 5: Display Departments with Salary Above 50,000

Write a query that displays matching employee and department information when the employee salary is above 50,000. Observe that departments without qualifying employees will not appear if the condition is placed in WHERE.

SELECT
    d.department_name,
    e.employee_name,
    e.salary
FROM employees AS e
RIGHT JOIN departments AS d
    ON e.department_id = d.department_id
WHERE e.salary > 50000;

23. Interview Questions and Answers

Q1. What is RIGHT JOIN in MySQL?

Answer: RIGHT JOIN returns all rows from the right-hand table and matching rows from the left-hand table. Unmatched right-hand rows contain NULL values for left-hand columns.

Q2. What is the difference between RIGHT JOIN and RIGHT OUTER JOIN?

Answer: They are equivalent in MySQL. The OUTER keyword is optional.

Q3. Which table is preserved in RIGHT JOIN?

Answer: The table written after the RIGHT JOIN keyword is preserved in full.

Q4. What happens when a row has no match?

Answer: The right-hand row remains in the result, and the columns from the left-hand table contain NULL.

Q5. Can RIGHT JOIN be rewritten as LEFT JOIN?

Answer: Yes. Reverse the order of the tables and use LEFT JOIN to preserve the same table.

Q6. Can RIGHT JOIN be used with GROUP BY?

Answer: Yes. It can be combined with GROUP BY and aggregate functions to create summaries for every row group represented by the preserved table.

Q7. How can you find unmatched records from the right-hand table?

Answer: Use RIGHT JOIN and filter for NULL in a suitable non-NULLable column from the left-hand table.

Q8. What is the difference between ON and WHERE?

Answer: ON defines how rows match. WHERE filters the resulting rows. A WHERE condition on the non-preserved table can remove unmatched rows from an outer join.

Q9. Why use COUNT(employee_id) instead of COUNT(*)?

Answer: COUNT(employee_id) ignores NULL values and counts only matching employees when employee_id is non-NULL for actual employee records. COUNT(*) also counts preserved rows without an employee match.

Q10. Does RIGHT JOIN always return the same number of rows as the right-hand table?

Answer: No. The result may contain more rows when a right-hand record matches multiple left-hand records. It preserves every right-hand row but does not guarantee one output row per right-hand row.

Q11. Can RIGHT JOIN connect more than two tables?

Answer: Yes. Multiple joins can be combined in a query, but join order and join types affect which rows remain in the final result.

Q12. How can RIGHT JOIN performance be improved?

Answer: Use correct join conditions, suitable indexes, compatible column types, explicit column lists, and EXPLAIN to examine the query execution plan.

24. Quick Revision Checklist

  • RIGHT JOIN preserves all rows from the right-hand table.
  • Matching rows from the left-hand table are included.
  • Unmatched right-hand rows have NULL values in left-hand columns.
  • The ON clause specifies the matching condition.
  • RIGHT JOIN and RIGHT OUTER JOIN mean the same thing in MySQL.
  • Table aliases make queries easier to read.
  • WHERE filters joined rows and can remove unmatched records.
  • GROUP BY and aggregate functions generate summaries.
  • COUNT(non_nullable_column) counts matching records without counting NULL values.
  • Use IS NULL to identify unmatched records.
  • RIGHT JOIN can be rewritten as LEFT JOIN by reversing the table order.
  • Use EXPLAIN and appropriate indexes when investigating performance.

25. Conclusion

RIGHT JOIN is an important MySQL concept for retrieving all records from a chosen right-hand table, even when corresponding records do not exist in the left-hand table. It is useful for reports that must include every department, course, product, account, or other reference record regardless of whether related activity exists.

By understanding the ON clause, table aliases, NULL values, filtering, grouping, and aggregate functions, you can write RIGHT JOIN queries for practical database reporting. Always identify which table must be preserved and test your queries with both matching and unmatched records.

Continue Learning: Visit the MySQL Training Course to continue learning SQL concepts, and use the course demo registration page to explore the training.

whatsapp